const path = require('path')
const webpack = require('webpack')
// const GitRevisionPlugin = require('git-revision-webpack-plugin')
// const GitRevision = new GitRevisionPlugin()
const buildDate = JSON.stringify(new Date().toLocaleString())
const createThemeColorReplacerPlugin = require('./config/plugin.config')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
function resolve(dir) {
  return path.join(__dirname, dir)
}

const isProd = process.env.NODE_ENV === 'production'

const assetsCDN = {
  // webpack build externals
  externals: {
    // vue: 'Vue',
    // 'vue-router': 'VueRouter',
    // vuex: 'Vuex',
    // axios: 'axios'
  },
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    '//cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js',
    '//cdn.jsdelivr.net/npm/vue-router@3.1.3/dist/vue-router.min.js',
    '//cdn.jsdelivr.net/npm/vuex@3.1.1/dist/vuex.min.js',
    '//cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js'
  ]
}

// vue.config.js
const vueConfig = {
  configureWebpack: {
    // webpack plugins
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        APP_VERSION: `"${require('./package.json').version}"`,
        // GIT_HASH: JSON.stringify(GitRevision.version()),
        BUILD_DATE: buildDate
      }),
      new CopyWebpackPlugin({
        patterns: [
          {
            from: './static',
            to: 'static'
          }
        ]
      }),
      // 开启gzip压缩
      new CompressionWebpackPlugin({
        test: /\.js$|\.html$|\.css/, // 匹配文件后缀名
        threshold: 10240, // 对超过10kb文件进行压缩
        deleteOriginalAssets: false // 是否删除源文件
      })
    ],
    // if prod, add externals
    externals: isProd ? assetsCDN.externals : {}
  },

  chainWebpack: config => {
    config.resolve.alias.set('@$', resolve('src')) // svg 规则

    const svgRule = config.module.rule('svg') // 找到原有的svg-loader
    svgRule.uses.clear() // 清除已有的loader, 如果不清除会在原有loader之后再使用当前loader规则
    svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录
    svgRule // 添加svg新的loader处理
      .test(/\.svg$/)
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      }) // 修改images loader，添加svg处理

    const imagesRule = config.module.rule('images')
    imagesRule.exclude.add(resolve('src/assets/svg'))
    config.module.rule('images').test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)

    config.module.rule('bim').test(/\.dat$/).use('file-loader').loader('file-loader')
    // if prod is on
    // assets require on cdn
    if (isProd) {
      config.plugin('html').tap(args => {
        args[0].cdn = assetsCDN
        return args
      })
    }

    //分析代码用，npm run analy
    if (process.env.NODE_ENV === 'production') {
      if (process.env.npm_config_report) {
        config
          .plugin('webpack-bundle-analyzer')
          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
          .end()
        config.plugins.delete('prefetch')
      }
    }
  },

  css: {
    loaderOptions: {
      less: {
        modifyVars: {
          // less vars，customize ant design theme

          // 'primary-color': '#F5222D',
          // 'link-color': '#F5222D',
          'border-radius-base': '2px'
        },
        // DO NOT REMOVE THIS LINE
        javascriptEnabled: true
      }
    }
  },
  devServer: {
    open: true,
    overlay: {
      warnings: false,
      errors: false
    },
    disableHostCheck: true,
    // development server port 8000
    port: 8000,
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
    proxy: {
      '/api/mock': {
        target: 'http://192.168.128.52:3000',
        changeOrigin: true, //是否跨域
        pathRewrite: {
          //需要rewrite重写的,
          '/api/mock': '/mock'
        }
      },
      '/api': {
        // target: 'http://localhost:9000',
        // target: 'https://testpm.cscecxn.com/api/', //uat
      //  target: 'http://mzuul.zj8j.cddev.cddpi.com',
        target: 'http://zuul.zj8j.cdtest.cddpi.com', //测试
        // target: 'http://admin.zj8j.cdtest.cddpi.com/api/',
        changeOrigin: true, //是否跨域
        pathRewrite: {
          //需要rewrite重写的,
          '/api': '/'
        }
      },
      //第三方看板对接跨域
      '/sdata': {
        target: 'http://192.168.128.14:8080',
        changeOrigin: true, //是否跨域
        pathRewrite: {
          //需要rewrite重写的,
          '/sdata': '/sdata'
        }
      }
    }
  },

  // disable source map in production
  productionSourceMap: false,
  lintOnSave: false,
  // babel-loader no-ignore node_modules/*
  //下面的库，不会被babel忽略，因为要打包到ie上
  transpileDependencies: ['vue-copy-to-clipboard']
}

// preview.pro.loacg.com only do not use in your production;
if (process.env.VUE_APP_PREVIEW === 'true') {
  console.log('VUE_APP_PREVIEW', true)
  // add `ThemeColorReplacer` plugin to webpack plugins
  vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}

module.exports = vueConfig
